import { useHistory, useLocation } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'

import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getSearchResults } from '@/store/actions/search'
import { RootAction, RootState } from '@/types/store'
import ArticleItem from '@/pages/Home/ArticleItem'

const Result = () => {
  const history = useHistory()
  const location = useLocation()
  // console.log(location.search)
  const keyword = new URLSearchParams(location.search).get('keyword')
  // console.log(keyword)
  const dispatch = useDispatch()

  // useEffect(() => {
  //   dispatch(getSearchResults(keyword!, 1))
  // }, [dispatch, keyword])

  // 获取仓库中的搜索结果数据
  const { results } = useSelector((state: RootState) => state.search)

  const [page, setPage] = useState(1)

  // 问题：搜索js 出现搜索结果； 搜索vue 出现的搜索结果和上次搜索结果竟然是一样的！！！
  // 分析：搜索结果页用的是仓库中的数据，退出搜索结果页后并没有清空仓库中的数据
  // 解决：退出搜索结果页面时，清空仓库数据！！！
  useEffect(() => {
    return () => {
      // 清空仓库数据
      dispatch({
        type: 'search/clear_results',
      } as RootAction)
    }
  }, [dispatch])

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => {
          return (
            <div
              className="article-item"
              key={item.art_id}
              onClick={() => {
                history.push('/article/' + item.art_id)
              }}
            >
              <ArticleItem article={item} type={item.cover.type}></ArticleItem>
            </div>
          )
        })}

        <InfiniteScroll
          hasMore={page <= 5}
          loadMore={async () => {
            // 这里必须等数据回来，因为有数据将来才有结构，将来才不会无脑触底！！！
            await dispatch(getSearchResults(keyword!, page))
            setPage(page + 1)
          }}
        ></InfiniteScroll>
      </div>
    </div>
  )
}

export default Result
